<template>
  <view class="warehouse-container">
    <!-- 当前仓库信息 -->
    <view class="warehouse-info-section">
      <view class="warehouse-info-card">
        <view class="warehouse-icon">
          <text class="icon-text">🏭</text>
        </view>
        <view class="warehouse-content">
          <text class="warehouse-label">当前工序</text>
          <text class="warehouse-name">{{ currentProcess }}</text>
        </view>

        <view class="card-item">
          <text class="number">{{ overview.totalWeight }} KG</text>
          <text class="label">今日计划量</text>
        </view>
        <view class="card-item">
          <text class="number">{{ overview.totalAmount }} KG</text>
          <text class="label">今日产量</text>
        </view>
        <view class="card-item">
          <text class="number">{{ overview.todayIn }} %</text>
          <text class="label">一次投兑率</text>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">数据加载中...</text>
    </view>

    <!-- 主要内容区域 -->
    <view class="content-wrapper">
      <!-- 仓库作业模块 -->
      <view class="operation-section">
        <view class="section-header">
          <text class="section-title">细丝作业</text>
          <text class="section-tag">核心功能</text>
        </view>

        <view class="operation-grid">
          <view
            v-for="menu in operationMenus"
            :key="menu.path"
            class="operation-item"
            :class="{ 'out-warehouse': menu.path === 'record' }"
            @tap="navigateTo(menu.path)"
          >
            <view
              class="operation-icon"
              :class="menu.path === 'record' ? 'out-warehouse' : ''"
            >
              <text class="icon-text">{{ menu.icon }}</text>
            </view>
            <view class="operation-content">
              <text class="operation-title">{{ menu.title }}</text>
              <text class="operation-desc">{{ menu.desc }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 记录查询模块 -->
      <view class="query-section">
        <view class="section-header">
          <text class="section-title">记录查询</text>
          <text class="section-tag">数据查询</text>
        </view>

        <view class="query-grid">
          <view
            v-for="menu in queryMenus"
            :key="menu.path"
            class="query-item"
            :class="{ 'in-record': menu.path === 'in-record' }"
            @tap="navigateTo(menu.path)"
          >
            <view
              class="query-icon"
              :class="menu.path === 'in-record' ? 'in-record' : ''"
            >
              <text class="icon-text">{{ menu.icon }}</text>
            </view>
            <view class="query-content">
              <text class="query-title">{{ menu.title }}</text>
              <text class="query-desc">{{ menu.desc }}</text>
              <view
                v-if="menu.path === 'in-record' && inRecordCount > 0"
                class="record-badge"
                >{{ inRecordCount }}</view
              >
            </view>
          </view>

          <!-- 出库记录 -->
          <!-- <view class="query-item" @tap="navigateTo('out-record')">
            <view class="query-icon out-record">
              <text class="icon-text">📋</text>
            </view>
            <view class="query-content">
              <text class="query-title">细丝记录</text>
              <text class="query-desc">查看细丝记录</text>
              <view v-if="outRecordCount > 0" class="record-badge">{{
                outRecordCount
              }}</view>
            </view>
          </view> -->
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
import { inventoryApi } from "@/api/warehouse/inventory";

export default {
  data() {
    return {
      currentWarehouse: {
        id: 1,
        name: "原料仓库A",
      },
      overview: {
        currentPlan: "",
        totalWeight: 0,
        totalAmount: 0,
        todayIn: 0,
        todayOut: 0,
      },
      loading: false,
      // 记录统计数据
      inRecordCount: 12,
      outRecordCount: 8,
      // 当前工序名称
      currentProcess: "",
      // 静态菜单数组
      staticMenus: [
        // 细丝作业模块
        {
          matchTitle: "APP-细丝作业",
          title: "细丝作业",
          path: "record",
          icon: "📋",
          desc: "执行细丝作业",
          type: "operation",
        },
        // 记录查询模块
        {
          matchTitle: "APP-细丝记录",
          title: "细丝记录",
          path: "in-record",
          icon: "📝",
          desc: "查看细丝记录",
          type: "query",
        },
      ],
    };
  },

  computed: {
    ...mapGetters(["menus"]),
    allowedMenus() {
      // 获取动态菜单数据，如果菜单不存在则默认空数组
      const dynamicMenus = this.menus || [];
      // 先筛选出动态菜单中的顶级菜单项（parentId=0）且name=APP-细丝生产
      const parentMenu = dynamicMenus.find(
        (dynamicMenu) =>
          dynamicMenu.parentId === 0 && dynamicMenu.name === "APP-细丝生产"
      );
      // 如果没有找到父菜单，则返回空数组
      if (!parentMenu || !parentMenu.children) {
        return [];
      }
      // 获取父菜单的所有子节点
      const childMenus = parentMenu.children || [];
      // 筛选出静态路由与动态路由子节点匹配的项，返回静态路由信息
      const filteredMenus = this.staticMenus.filter((staticMenu) =>
        childMenus.some((childMenu) => childMenu.name === staticMenu.matchTitle)
      );
      return filteredMenus;
    },
    // 暴露filteredMenus供模板使用
    filteredMenus() {
      return this.allowedMenus;
    },
    // 分模块的菜单
    operationMenus() {
      return this.filteredMenus.filter((menu) => menu.type === "operation");
    },
    queryMenus() {
      return this.filteredMenus.filter((menu) => menu.type === "query");
    },
  },

  onLoad() {
    this.initWarehouseData();
    this.initCurrentProcess();
    this.loadDashboardData();
  },

  methods: {
    // 初始化当前工序
    initCurrentProcess() {
      try {
        const userConfig = this.$store.state.user.userConfig || {};
        const workInfo = this.$store.state.user.workInfo || {};

        // 从用户配置中获取工序名称，支持多种字段格式
        let processName = "";
        if (userConfig.processName) {
          processName = userConfig.processName;
        } else if (userConfig.process_name) {
          processName = userConfig.process_name;
        } else if (workInfo.processName) {
          processName = workInfo.processName;
        } else if (workInfo.process_name) {
          processName = workInfo.process_name;
        } else if (workInfo.process) {
          processName = workInfo.process;
        } else if (userConfig.process) {
          processName = userConfig.process;
        }

        // 设置当前工序名称，如果没有获取到则使用默认值
        this.currentProcess = processName || "炼轧工序";

        console.log("当前工序初始化完成:", this.currentProcess);
      } catch (error) {
        console.error("初始化当前工序失败:", error);
        this.currentProcess = "炼轧工序"; // 错误时使用默认值
      }
    },

    async getCurrentWarehouse() {
      try {
        // 从Vuex store获取用户配置的仓库信息
        const userConfig = this.$store.state.user.userConfig;
        if (userConfig && userConfig.wmName) {
          return {
            warehouseId: userConfig.warehouseId || "DEFAULT",
            warehouseName: userConfig.wmName,
          };
        }

        // 降级处理：尝试其他字段
        if (userConfig && userConfig.warehouseName) {
          return {
            warehouseId: userConfig.warehouseId || "DEFAULT",
            warehouseName: userConfig.warehouseName,
          };
        }
      } catch (error) {
        console.error("获取用户仓库失败:", error);
      }

      // 默认值
      return {
        warehouseId: "DEFAULT",
        warehouseName: "默认仓库",
      };
    },

    async initWarehouseData() {
      try {
        // 获取当前仓库信息
        const currentWarehouse = await this.getCurrentWarehouse();
        if (currentWarehouse && currentWarehouse.warehouseName) {
          this.currentWarehouse = {
            id: currentWarehouse.warehouseId,
            name: currentWarehouse.warehouseName,
          };
        }
      } catch (error) {
        console.error("获取仓库信息失败:", error);
      }
    },

    async loadDashboardData() {
      this.loading = true;
      try {
        // 获取当前仓库信息
        const currentWarehouse = await this.getCurrentWarehouse();
        const warehouseName = currentWarehouse.warehouseName;
        const today = new Date().toISOString().split("T")[0];

        // 确定real_type
        let realType = "原料";
        if (warehouseName.includes("五金")) {
          realType = "五金";
        } else if (warehouseName.includes("备件")) {
          realType = "备件";
        }

        // 并行获取所有数据
        const [stockRes, inRes, outRes] = await Promise.all([
          // inventoryApi.getStockAmount({
          //   realType,
          //   warehouseName,
          //   busStatus: "已入库",
          // }),
          // inventoryApi.getStockInAmount({
          //   warehouseName,
          //   busStatus: "已入库",
          //   ywDate: today,
          // }),
          // inventoryApi.getStockOutAmount({
          //   warehouseName,
          //   busStatus: "已出库",
          //   ywDate: today,
          // }),
        ]);

        // 更新数据
        this.overview = {
          currentPlan: "炼轧计划",
          // totalWeight: stockRes.prodCount || 0,
          // totalAmount: this.formatToWan(stockRes.sumAmount || 0),
          // todayIn: inRes.prodCount || 0,
          // todayOut: outRes.prodCount || 0,
          totalWeight: 0,
          totalAmount: 0,
          todayIn: 0,
          todayOut: 0,
        };
      } catch (error) {
        console.error("加载仪表盘数据失败:", error);
        uni.showToast({
          title: "数据加载失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    formatToWan(amount) {
      if (!amount) return 0;
      return (amount / 10000).toFixed(2);
    },
    navigateTo(type) {
      const routes = {
        // 细丝作业模块
        record: "/pages/smart/03xsRecord/record",
        // 记录查询模块
        "in-record": "/pages/smart/warehouse/report/stockIn",
        "inventory-query": "/pages/smart/warehouse/inventory/query",
      };

      if (routes[type]) {
        uni.navigateTo({
          url: routes[type],
        });
      } else {
        uni.showToast({
          title: "功能开发中...",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.warehouse-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20rpx;
}

.page-header {
  text-align: center;
  margin-bottom: 30rpx;
  padding: 30rpx 0;

  .page-title {
    font-size: 36rpx;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 8rpx;
    background: linear-gradient(45deg, #1890ff, #096dd9);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }

  .page-subtitle {
    font-size: 24rpx;
    color: #7f8c8d;
    font-weight: 400;
  }
}

.overview-section {
  margin-bottom: 30rpx;
}

.overview-card {
  display: flex;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  justify-content: space-between;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.card-item {
  text-align: center;
  flex: 1;
}

.number {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 10rpx;
}

.label {
  font-size: 22rpx;
  color: #666;
}

// 仓库信息区域
.warehouse-info-section {
  margin-bottom: 30rpx;
}

.warehouse-info-card {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  border-left: 8rpx solid #1890ff;
}

.warehouse-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #1890ff, #096dd9);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;

  .icon-text {
    color: white;
    font-size: 40rpx;
  }
}

.warehouse-content {
  flex: 1;
}

.warehouse-label {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
  display: block;
}

.warehouse-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  display: block;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  margin-bottom: 20rpx;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #666;
}

.content-wrapper {
  display: grid;
  gap: 30rpx;
  padding: 0 10rpx;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30rpx;
  padding: 0 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.section-tag {
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  background: #1890ff;
  color: white;
  font-weight: 500;
}

.query-section .section-tag {
  background: #52c41a;
}

.operation-grid,
.query-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.operation-item,
.query-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 30rpx 20rpx;
  background: white;
  border-radius: 20rpx;
  border: 2rpx solid #e8e8e8;
  transition: all 0.3s ease;
  position: relative;

  &:active {
    transform: scale(0.98);
    background-color: #f8f9fa;
  }

  &.reverse {
    border-color: #ff4d4f;

    &:active {
      background-color: #fff5f5;
    }
  }
}

.operation-icon,
.query-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40rpx;

  &.in-warehouse {
    background: linear-gradient(135deg, #52c41a, #73d13d);
  }

  &.out-warehouse {
    background: linear-gradient(135deg, #1890ff, #40a9ff);
  }

  &.check-warehouse {
    background: linear-gradient(135deg, #722ed1, #9254de);
  }

  &.in-reverse,
  &.out-reverse {
    background: linear-gradient(135deg, #ff4d4f, #ff7875);
  }

  &.in-record {
    background: linear-gradient(135deg, #52c41a, #73d13d);
  }

  &.out-record {
    background: linear-gradient(135deg, #1890ff, #40a9ff);
  }

  &.stock-query {
    background: linear-gradient(135deg, #fa8c16, #ffa940);
  }

  &.check-record {
    background: linear-gradient(135deg, #722ed1, #9254de);
  }

  &.in-reverse-record,
  &.out-reverse-record {
    background: linear-gradient(135deg, #ff4d4f, #ff7875);
  }
}

.icon-text {
  color: white;
  font-size: 40rpx;
}

.operation-content,
.query-content {
  flex: 1;

  .operation-title,
  .query-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 8rpx;
  }

  .operation-desc,
  .query-desc {
    font-size: 22rpx;
    color: #7f8c8d;
    margin: 0;
  }
}

.record-badge {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  background: #ff4d4f;
  color: white;
  border-radius: 50%;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
  font-weight: bold;
}

// 响应式设计
@media (max-width: 480px) {
  .warehouse-info-card {
    padding: 20rpx;
  }

  .warehouse-icon {
    width: 60rpx;
    height: 60rpx;
    margin-right: 15rpx;

    .icon-text {
      font-size: 32rpx;
    }
  }

  .warehouse-name {
    font-size: 28rpx;
  }

  .overview-card {
    padding: 20rpx;
  }

  .card-item {
    padding: 10rpx;
  }

  .number {
    font-size: 24rpx;
  }

  .label {
    font-size: 20rpx;
  }

  .operation-grid,
  .query-grid {
    grid-template-columns: 1fr;
  }

  .operation-item,
  .query-item {
    padding: 20rpx;
  }

  .operation-icon,
  .query-icon {
    width: 60rpx;
    height: 60rpx;
    font-size: 32rpx;
  }

  .icon-text {
    font-size: 32rpx;
  }

  .operation-title,
  .query-title {
    font-size: 24rpx;
  }

  .operation-desc,
  .query-desc {
    font-size: 20rpx;
  }
}

// 加载动画
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 仓库信息卡片动画
.warehouse-info-section {
  animation: fadeInUp 0.6s ease-out;
}

.warehouse-info-card {
  transition: all 0.3s ease;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.15);
  }

  // 悬停效果
  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 8rpx 25rpx rgba(24, 144, 255, 0.2);
  }
}

.warehouse-name {
  transition: color 0.3s ease;

  &:hover {
    color: #1890ff;
  }
}

// 仓库图标动画
.warehouse-icon {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

// 概览卡片悬停效果
.overview-card {
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.15);
  }
}

// 功能项悬停动画
.operation-item,
.query-item {
  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
  }

  // 图标悬停旋转效果
  &:hover .operation-icon,
  &:hover .query-icon {
    animation: rotate 0.6s ease-in-out;
  }
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.operation-section,
.query-section {
  animation: fadeInUp 0.6s ease-out;
}
</style>
